package com.qq.weixin.service;

import java.io.IOException;
import java.text.MessageFormat;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.qq.weixin.model.BaseResult;
import com.qq.weixin.model.ResultInfo;
import com.qq.weixin.model.tpl.TemplateSendMsg;

public class TemplateService {
  Logger logger = Logger.getLogger(TemplateService.class);
  private JsonParser parser = new JsonParser();
  private Gson gson = new Gson();
  private CloseableHttpClient httpclient = HttpClients.createDefault();

  public BaseResult sendMessage(String accessToken, TemplateSendMsg msg) {
    HttpPost postReq = new HttpPost(MessageFormat.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}",
        accessToken));
    BaseResult result = new BaseResult();
    CloseableHttpResponse postResp = null;
    try {
      postReq.setEntity(new StringEntity(gson.toJson(msg), "utf-8"));
      postResp = httpclient.execute(postReq);
      String jsonstr = EntityUtils.toString(postResp.getEntity());
      JsonElement element = parser.parse(jsonstr);
      ResultInfo resultInfo = ResultInfo.convert(element);
      result.setResultInfo(resultInfo);
      if (resultInfo.isSuccess()) {
        result.setMsgid(element.getAsJsonObject().get("msgid").getAsBigInteger().longValue());
      }

    } catch (Exception e) {
      logger.error("", e);
    } finally {
      if (postResp != null) {
        try {
          postResp.close();
        } catch (IOException e) {
          logger.error("", e);
        }
      }
    }
    return result;
  }
}
